﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Threading;

namespace TheOliver.Controls
{

	/// <summary>
	/// Trigger that occurs based on a timer.
	/// </summary>
	public class TimerTrigger : TriggerBase<FrameworkElement> {

		DispatcherTimer timer;

		/// <summary>
		/// 
		/// </summary>
		public static readonly DependencyProperty IntervalProperty = DependencyProperty.Register("Interval", typeof(TimeSpan), typeof(TimerTrigger), new PropertyMetadata(TimeSpan.FromSeconds(1)));
		/// <summary>
		/// 
		/// </summary>
		public static readonly DependencyProperty RepeatProperty = DependencyProperty.Register("Repeat", typeof(bool), typeof(TimerTrigger), new PropertyMetadata(true));

		/// <summary>
		/// True if this should be repeating.
		/// </summary>
		public bool Repeat {
			get { return (bool)this.GetValue(TimerTrigger.RepeatProperty); }
			set { this.SetValue(TimerTrigger.RepeatProperty, value); }
		}

		/// <summary>
		/// Determines the amount of time between timer ticks.
		/// </summary>
		public TimeSpan Interval {
			get { return (TimeSpan)this.GetValue(TimerTrigger.IntervalProperty); }
			set { this.SetValue(TimerTrigger.IntervalProperty, value); }
		}

		/// <summary>
		/// Sets everything up when getting attached.
		/// </summary>
		protected override void OnAttached() {
			base.OnAttached();

			this.timer = new DispatcherTimer() {
				Interval = this.Interval,
			};

			this.timer.Tick += this.HandleTick;
			this.timer.Start();
		}

		/// <summary>
		/// Cleans up when getting removed.
		/// </summary>
		protected override void OnDetaching() {
			base.OnDetaching();

			this.timer.Stop();
		}

		private void HandleTick(object sender, EventArgs e) {
			if (!this.Repeat)
				this.timer.Stop();

			this.InvokeActions(null);
		}
	}
}
